package com.kcwl.carrier.application.service;

import cn.hutool.core.util.StrUtil;
import com.kcwl.account.interfaces.api.ICarrierAccountService;
import com.kcwl.account.interfaces.dto.carrier.account.CarrierAccountDTO;
import com.kcwl.account.interfaces.enums.ShipperAccountStatusEnum;
import com.kcwl.account.interfaces.query.carrier.CarrierAccountBatchQuery;
import com.kcwl.carrier.application.assembler.CarrierInfoAssembler;
import com.kcwl.carrier.domain.bo.CarrierDetailInfoBO;
import com.kcwl.carrier.domain.entity.*;
import com.kcwl.carrier.domain.factory.CarrierCompanyInfoFactory;
import com.kcwl.carrier.domain.factory.CarrierCooperateInfoFactory;
import com.kcwl.carrier.domain.factory.CarrierInfoFactory;
import com.kcwl.carrier.domain.service.CarrierInfoDomainService;
import com.kcwl.carrier.domain.service.CarrierMappingDomainService;
import com.kcwl.carrier.domain.service.QualificationInfoDomainService;
import com.kcwl.carrier.domain.service.VehicleInfoDomainService;
import com.kcwl.carrier.infrastructure.config.SecurityConfig;
import com.kcwl.carrier.infrastructure.constant.CarrierConstant;
import com.kcwl.carrier.infrastructure.enums.*;
import com.kcwl.carrier.infrastructure.exceptions.CarrierUserException;
import com.kcwl.carrier.infrastructure.utils.DateUtil;
import com.kcwl.carrier.infrastructure.utils.RedisLocalKeyUtil;
import com.kcwl.carrier.interfaces.command.*;
import com.kcwl.carrier.interfaces.dto.*;
import com.kcwl.carrier.interfaces.query.*;
import com.kcwl.ddd.application.constants.IdentityTypeEnum;
import com.kcwl.ddd.application.constants.YesNoEnum;
import com.kcwl.ddd.domain.entity.KcPage;
import com.kcwl.ddd.infrastructure.api.ResponseMessage;
import com.kcwl.ddd.infrastructure.utils.KcPageConverter;
import com.kcwl.ddd.interfaces.dto.PageInfoDTO;
import com.kcwl.euc.interfaces.api.IAuthService;
import com.kcwl.euc.interfaces.api.IUserBaseService;
import com.kcwl.euc.interfaces.command.DelUserCommand;
import com.kcwl.euc.interfaces.command.UserApproveCommand;
import com.kcwl.euc.interfaces.command.UserCommand;
import com.kcwl.euc.interfaces.dto.UserInfoDTO;
import com.kcwl.euc.interfaces.query.UserBaseInfoQuery;
import com.kcwl.file.interfaces.api.IFileRemoteService;
import com.kcwl.file.interfaces.dto.FileUrlDTO;
import com.kcwl.file.interfaces.query.FileUrlQuery;
import com.kcwl.framework.cache.ICacheService;
import com.kcwl.framework.utils.CollectionUtil;
import com.kcwl.framework.utils.KcBeanConverter;
import com.kcwl.framework.utils.StringUtil;
import com.kcwl.mdm.interfaces.api.IAreaService;
import com.kcwl.mdm.interfaces.dto.AreaDTO;
import com.kcwl.mdm.interfaces.query.AreaQuery;
import com.kcwl.partner.interfaces.api.IContractInfoService;
import com.kcwl.partner.interfaces.api.IEnterpriseService;
import com.kcwl.partner.interfaces.dto.ContractPageDTO;
import com.kcwl.partner.interfaces.dto.EnterpriseDTO;
import com.kcwl.partner.interfaces.query.ContractRunningQuery;
import com.kcwl.partner.interfaces.query.EnterpriseQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 刘旭超
 * @date 2022年07月08日 15:35
 * @Description
 */
@Service
@Slf4j
public class CarrierUserApplicationService {

    @Autowired
    private IUserBaseService userBaseService;

    @Autowired
    private ICacheService stringCache;

    @Autowired
    private CarrierInfoDomainService carrierInfoDomainService;

    @Autowired
    private SecurityConfig securityConfig;

    @Autowired
    private IAuthService authService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private VehicleInfoDomainService vehicleInfoDomainService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IContractInfoService contractInfoService;

    @Autowired
    private OperateLogApplicationService operateLogApplicationService;

    @Autowired
    private QualificationInfoDomainService qualificationInfoDomainService;

    @Resource
    private AuditRejectReasonApplicationService auditRejectReasonApplicationService;

    @Autowired
    private IFileRemoteService fileRemoteService;

    @Autowired
    CarrierConfigApplicationService carrierConfigApplicationService;

    @Autowired
    CarrierMappingDomainService carrierMappingDomainService;

    @Autowired
    ICarrierAccountService carrierAccountService;

    @Autowired
    CarrierDriverApplicationService carrierDriverApplicationService;

    /**
     * 查询司机认证信息
     */
    public CarrierApproveInfoDTO queryUserApproveInfo(CarrierInfoQuery carrierInfoQuery) {
        // 获取用户信息
        UserInfoDTO userInfoDTO = getUserById(carrierInfoQuery.getUserId());
        // 司机信息
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierInfoQuery.getUserId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.AUTH_IS_NOT_EXISTS);
        }
        // 辅助人信息
        CarrierCooperateInfo carrierCooperateInfo = carrierInfoDomainService.queryInitCooperateInfo(carrierInfo.getId());
        // 物流公司信息
        CarrierCompanyInfo carrierCompanyInfo = carrierInfoDomainService.queryCompayInfoByCarrierId(carrierInfo.getId());
        // 驳回原因
        List<AuditRejectReasonInfoDTO> rejectReasonInfoDTOList = auditRejectReasonApplicationService.queryAllRejectReason();
        Map<Long, String> rejectMap = rejectReasonInfoDTOList.stream().collect(Collectors.toMap(AuditRejectReasonInfoDTO::getId, AuditRejectReasonInfoDTO::getReason));
        return CarrierInfoAssembler.createCarrierApproveInfo(userInfoDTO, carrierInfo, carrierCompanyInfo, carrierCooperateInfo, rejectMap);
    }

    /**
     * 通过用户ID获取用户信息
     * @param userId
     * @return
     */
    public UserInfoDTO getUserById(Long userId) {
        UserBaseInfoQuery userBaseInfoQuery = new UserBaseInfoQuery();
        userBaseInfoQuery.setId(userId);
        ResponseMessage<UserInfoDTO> responseMessage = userBaseService.queryById(userBaseInfoQuery);
        UserInfoDTO userInfoDTO = responseMessage.getResult();
        if (userInfoDTO == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.USER_IS_NOT_EXISTS);
        }
        return userInfoDTO;
    }

    /**
     * 查询司机用户信息
     */
    public CarrierCenterInfoDTO queryUserInfo(CarrierInfoQuery carrierInfoQuery) {
        // 获取用户信息
        UserInfoDTO userBaseInfo = getUserById(carrierInfoQuery.getUserId());
        // 获取司机信息
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierInfoQuery.getUserId());
        // 获取物流公司信息
        CarrierCompanyInfo carrierCompanyInfo = carrierInfoDomainService.queryCompayInfoByCarrierId(carrierInfoQuery.getUserId());
        // 获取车辆信息
        List<VehicleInfo> vehicleInfoList = vehicleInfoDomainService.getVehicleListByCarrierId(carrierInfoQuery.getUserId());
        return CarrierInfoAssembler.createCarrierCenterInfo(userBaseInfo, carrierInfo, carrierCompanyInfo, vehicleInfoList);
    }

    /**
     * 个体司机审核信息列表查询
     */
    public PageInfoDTO<SingleCarrierInfoListDTO> querySingleList(SingleCarrierInfoListQuery query) {
        SingleCarrierInfoListCondition singleCarrierInfoListCondition = KcBeanConverter.toBean(query, SingleCarrierInfoListCondition.class);
        KcPage<SingleCarrierListInfo> pageEntity = carrierInfoDomainService.querySingleList(singleCarrierInfoListCondition);
        List<SingleCarrierListInfo> list = pageEntity.getList();
        List<Long> carrierIds = list.stream().map(SingleCarrierListInfo::getCarrierId).collect(Collectors.toList());
        // 账号信息
        UserBaseInfoQuery userBaseInfoQuery = new UserBaseInfoQuery();
        userBaseInfoQuery.setIds(carrierIds);
        List<UserInfoDTO> userInfoDTOS = userBaseService.getByUserIds(userBaseInfoQuery).getResult();
        Map<Long, UserInfoDTO> userInfoDTOMap = userInfoDTOS.stream().collect(Collectors.toMap(UserInfoDTO::getId, UserInfoDTO -> UserInfoDTO));
        // 账户信息
        CarrierAccountBatchQuery carrierAccountBatchQuery = new CarrierAccountBatchQuery();
        carrierAccountBatchQuery.setCarrierIdList(carrierIds);
//        List<CarrierAccountDTO> carrierAccountDTOS = carrierAccountService.queryCarrierAccountInfoList(carrierAccountBatchQuery).getResult();
//        Map<Long, Integer> accountMap = carrierAccountDTOS.stream().collect(Collectors.toMap(CarrierAccountDTO::getCarrierId, carrierAccountDTO -> carrierAccountDTO.getAccountStatus()));
        //TODO 等结算上测试再打开
        Map<Long, Integer> accountMap = new HashMap<>();
        for (SingleCarrierListInfo singleCarrierListInfo : list) {
            UserInfoDTO dto = userInfoDTOMap.get(singleCarrierListInfo.getCarrierId());
            if (dto != null) {
                singleCarrierListInfo.setUserTag(dto.getUserTag());
                singleCarrierListInfo.setRegisterDate(dto.getCreateTime());
            }
            // 未查询到司机账户信息,默认是未激活
            singleCarrierListInfo.setAccountStatus(accountMap.get(singleCarrierListInfo.getCarrierId()) == null ? ShipperAccountStatusEnum.INITIALIZATION.getStatus() : accountMap.get(singleCarrierListInfo.getCarrierId()));
            singleCarrierListInfo.setHistoryRemarks(auditRejectReasonApplicationService.processRemark(singleCarrierListInfo.getHistoryRemark()));
        }
        return KcPageConverter.toPageInfoDTO(pageEntity, SingleCarrierInfoListDTO.class);
    }

    /**
     * 企业司机审核信息列表查询
     */
    public PageInfoDTO<FirmCarrierInfoListDTO> queryFirmList(FirmCarrierInfoListQuery query) {
        FirmCarrierInfoListCondition firmCarrierInfoListCondition = KcBeanConverter.toBean(query, FirmCarrierInfoListCondition.class);
        KcPage<FirmCarrierListInfo> pageEntity = carrierInfoDomainService.queryFirmList(firmCarrierInfoListCondition);
        List<FirmCarrierListInfo> list = pageEntity.getList();
        List<Long> carrierIds = list.stream().map(FirmCarrierListInfo::getCarrierId).collect(Collectors.toList());
        // 账号信息
        UserBaseInfoQuery userBaseInfoQuery = new UserBaseInfoQuery();
        userBaseInfoQuery.setIds(carrierIds);
        List<UserInfoDTO> userInfoDTOS = userBaseService.getByUserIds(userBaseInfoQuery).getResult();
        Map<Long, UserInfoDTO> userInfoDTOMap = userInfoDTOS.stream().collect(Collectors.toMap(UserInfoDTO::getId, UserInfoDTO -> UserInfoDTO));
        // 账户信息
        CarrierAccountBatchQuery carrierAccountBatchQuery = new CarrierAccountBatchQuery();
        carrierAccountBatchQuery.setCarrierIdList(carrierIds);
//        List<CarrierAccountDTO> carrierAccountDTOS = carrierAccountService.queryCarrierAccountInfoList(carrierAccountBatchQuery).getResult();
//        Map<Long, Integer> accountMap = carrierAccountDTOS.stream().collect(Collectors.toMap(CarrierAccountDTO::getCarrierId, carrierAccountDTO -> carrierAccountDTO.getAccountStatus()));
        //TODO 等结算上测试再打开
        Map<Long, Integer> accountMap = new HashMap<>();
        for (FirmCarrierListInfo firmCarrierListInfo : list) {
            UserInfoDTO dto = userInfoDTOMap.get(firmCarrierListInfo.getCarrierId());
            if (dto != null) {
                firmCarrierListInfo.setUserTag(dto.getUserTag());
                firmCarrierListInfo.setRegisterDate(dto.getCreateTime());
            }
            // 未查询到司机账户信息,默认是未激活
            firmCarrierListInfo.setAccountStatus(accountMap.get(firmCarrierListInfo.getCarrierId()));
            firmCarrierListInfo.setHistoryRemarks(auditRejectReasonApplicationService.processRemark(firmCarrierListInfo.getHistoryRemark()));
        }
        return KcPageConverter.toPageInfoDTO(pageEntity, FirmCarrierInfoListDTO.class);
    }

    /**
     * 司机详情查询
     */
    public CarrierDetailInfoDTO queryCarrierDetailInfo(Long carrierId) {
        // 司机信息组装辅助人和物流公司
        CarrierDetailInfoBO carrierDetailInfoBO = carrierInfoDomainService.queryCarrierDetailInfo(carrierId);
        CarrierDetailInfoDTO carrierDetailInfoDTO = KcBeanConverter.toBean(carrierDetailInfoBO, CarrierDetailInfoDTO.class);
        CarrierInfoDTO carrierInfo = carrierDetailInfoDTO.getCarrierInfo();
        carrierInfo.setAuthStatus(carrierDetailInfoBO.getCarrierInfo().getAuthenticationStatus());
        carrierInfo.setHistoryRemarks(auditRejectReasonApplicationService.processRemark(carrierInfo.getHistoryRemark()));
        // 用户信息
        UserInfoDTO userBaseInfo = getUserById(carrierInfo.getId());
        carrierDetailInfoDTO.setUserBaseInfo(KcBeanConverter.toBean(userBaseInfo, CarrierUserBaseInfoDTO.class));
        return carrierDetailInfoDTO;
    }

    /**
     * 司机认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void driverApprove(CarrierApproveCommand carrierApproveCommand) {
        carrierApprove(carrierApproveCommand, IdentityTypeEnum.CARRIER_DRIVER);
    }

    /**
     * 车老板认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void carrierBossApprove(CarrierApproveCommand carrierApproveCommand) {
        carrierApprove(carrierApproveCommand, IdentityTypeEnum.CARRIER_SFLTOP);
    }

    /**
     * 物流公司认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void carrierCompanyApprove(CarrierApproveCommand carrierApproveCommand) {
        carrierApprove(carrierApproveCommand, IdentityTypeEnum.CARRIER_TCOM_MANAGER);
    }

    /**
     * 运力辅助人认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void carrierAiderApprove(CarrierApproveCommand carrierApproveCommand) {
        carrierApprove(carrierApproveCommand, IdentityTypeEnum.CARRIER_BRKR);
    }

    /**
     * TMS运输公司认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void carrierCompanyTMS(CarrierApproveCommand carrierApproveCommand) {
        carrierApproveTMS(carrierApproveCommand, IdentityTypeEnum.CARRIER_TCOM_MANAGER);
    }

    /**
     * TMS辅助服务商认证
     */
    @Transactional(rollbackFor = Exception.class)
    public void carrierAuxiliaryTMS(CarrierApproveCommand carrierApproveCommand) {
        carrierApproveTMS(carrierApproveCommand, IdentityTypeEnum.CARRIER_TDSPR);
    }

    /**
     * 司机用户认证
     */
    public void carrierApprove(CarrierApproveCommand carrierApproveCommand, IdentityTypeEnum identity) {
        // 认证信息状态校验
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierApproveCommand.getUserId());
        if (carrierInfo != null) {
            if (carrierInfo.getAuthenticationStatus() == CarrierAuthStatusEnum.WAITING.getCode()) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_STATUS_COMMITTED);
            }
            if (carrierInfo.getAuthenticationStatus() == CarrierAuthStatusEnum.PASS.getCode()) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_STATUS_PASS);
            }
        }
        // 用户信息认证
        carrierIdMatch(carrierApproveCommand);
        // 保存认证信息
        saveCarrierApprove(carrierApproveCommand, identity, carrierInfo);
    }

    /**
     * TMS用户认证
     */
    public void carrierApproveTMS(CarrierApproveCommand carrierApproveCommand, IdentityTypeEnum identity) {
        // 认证信息状态校验
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierApproveCommand.getUserId());
        if (carrierInfo != null) {
            if (carrierInfo.getAuthenticationStatus() == CarrierAuthStatusEnum.WAITING.getCode()) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_STATUS_COMMITTED);
            }
            if (carrierInfo.getAuthenticationStatus() == CarrierAuthStatusEnum.PASS.getCode()) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_STATUS_PASS);
            }
        }
        // 保存认证信息
        saveCarrierApprove(carrierApproveCommand, identity, carrierInfo);
    }

    private void carrierIdMatch(CarrierApproveCommand carrierApproveCommand) {
        String key = RedisLocalKeyUtil.getIdCardMatchCount(carrierApproveCommand.getMobile());
        // 调用用户认证接口
        UserApproveCommand command = new UserApproveCommand();
        command.setRealName(carrierApproveCommand.getRealName());
        command.setIdCardNo(carrierApproveCommand.getIdCardNo());
        command.setMatchAudit(carrierApproveCommand.getMatchAudit());
        command.setIdCardAddress(carrierApproveCommand.getIdCardAddress());
        command.setIdCardBehind(carrierApproveCommand.getIdCardBehind());
        command.setIdCardFront(carrierApproveCommand.getIdCardFront());
        command.setBirthday(carrierApproveCommand.getBirthday());
        command.setIdCardStartTime(carrierApproveCommand.getIdCardStartTime());
        command.setIdCardEndTime(carrierApproveCommand.getIdCardEndTime());
        // TMS存在帮助第三人认证的情况
        command.setUserId(carrierApproveCommand.getUserId());
        authService.carrierApprove(command);
        String countStr = (String) stringCache.get(key);
        if (StrUtil.isNotBlank(countStr) && securityConfig.getIdMatchErrorLimit().equals(Integer.parseInt(countStr))) {
            carrierApproveCommand.setLabel(carrierApproveCommand.getLabel() + " " + CarrierConstant.ID_CARD_MATCH_ERROR_LABEL);
        }
    }

    /**
     * 保存司机用户认证信息
     */
    private void saveCarrierApprove(CarrierApproveCommand carrierApproveCommand, IdentityTypeEnum identity, CarrierInfo carrierInfo) {
        CarrierInfo carrierInfoSave;
        CarrierCooperateInfo carrierCooperateInfoSave = null;
        CarrierCompanyInfo carrierCompanyInfo = null;
        UserBaseInfoQuery userBaseInfoQuery = new UserBaseInfoQuery();
        userBaseInfoQuery.setId(carrierApproveCommand.getUserId());
        UserInfoDTO userInfoDTO = userBaseService.queryById(userBaseInfoQuery).getResult();
        if (userInfoDTO == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.USER_IS_NOT_EXISTS);
        }
        switch (identity) {
            // 司机
            case CARRIER_DRIVER:
                carrierInfoSave = CarrierInfoFactory.createDriverApproveInfo(carrierApproveCommand);
                carrierInfoSave.setVehicleBingingLimit(carrierConfigApplicationService.queryVehicleBingingLimit(CarrierConfigEnum.CARRIER_LIMIT.getId()));
                break;
            // 车老板
            case CARRIER_SFLTOP:
                carrierInfoSave = CarrierInfoFactory.createCarrierBossApproveInfo(carrierApproveCommand);
                carrierInfoSave.setVehicleBingingLimit(carrierConfigApplicationService.queryVehicleBingingLimit(CarrierConfigEnum.CARRIER_SFLTOP_LIMIT.getId()));
                cancelApproveCarrierBoss(carrierInfoSave, userInfoDTO);
                break;
            // 物流公司
            case CARRIER_TCOM_MANAGER:
                carrierInfoSave = CarrierInfoFactory.createCarrierCompanyApproveInfo(carrierApproveCommand);
                carrierInfoSave.setVehicleBingingLimit(carrierConfigApplicationService.queryVehicleBingingLimit(CarrierConfigEnum.CARRIER_COMPANY_LIMIT.getId()));
                carrierCompanyInfo = CarrierCompanyInfoFactory.createCarrierCompanyApproveInfo(carrierApproveCommand);
                break;
            // 运力辅助人
            case CARRIER_BRKR:
                carrierInfoSave = CarrierInfoFactory.createCarrierAiderInfo(carrierApproveCommand);
                carrierCooperateInfoSave = CarrierCooperateInfoFactory.createCarrierCooperateApproveInfo(carrierApproveCommand);
                carrierCooperateInfoSave = buildCooperateInfo(carrierCooperateInfoSave);
                cancelApproveAuxiliary(carrierInfoSave, userInfoDTO, carrierCooperateInfoSave);
                break;
            // 物流辅助服务商
            case CARRIER_TDSPR:
                carrierInfoSave = CarrierInfoFactory.createCarrierAuxiliaryInfo(carrierApproveCommand);
                carrierInfoSave.setVehicleBingingLimit(carrierConfigApplicationService.queryVehicleBingingLimit(CarrierConfigEnum.CARRIER_TDSPR_LIMIT.getId()));
                break;
            default:
                return;
        }
        // 解析省市区
        setAreaInfo(carrierInfoSave);
        if (carrierInfo == null) {
            // 新增
            carrierInfoSave.setUserTag(userInfoDTO.getUserTag());
            carrierInfoDomainService.addCarrierInfo(carrierInfoSave);
            if (carrierCompanyInfo != null) {
                carrierInfoDomainService.saveCompanyInfo(carrierCompanyInfo);
            }
            if (carrierCooperateInfoSave != null) {
                carrierInfoDomainService.saveInitCooperate(carrierCooperateInfoSave);
            }
            operateLogApplicationService.registCarrierLog(carrierInfoSave.getId(), carrierInfoSave.getMobile(), userInfoDTO.getCreateTime());
        } else {
            // 更新
            if (StrUtil.isNotBlank(carrierInfoSave.getLabel())) {
                carrierInfoSave.setLabel(carrierInfo.getLabel() + " " + carrierInfoSave.getLabel());
            }
            carrierInfoSave.setId(carrierInfo.getId());
            carrierInfoSave.setUserTag(userInfoDTO.getUserTag());
            carrierInfoDomainService.updateCarrierInfoById(carrierInfoSave);
            if (carrierCompanyInfo != null) {
                carrierCompanyInfo.setCarrierId(carrierInfo.getId());
                carrierInfoDomainService.updateCompanyByCarrierId(carrierCompanyInfo);
            }
            if (carrierCooperateInfoSave != null) {
                carrierCooperateInfoSave.setCarrierId(carrierInfo.getId());
                carrierInfoDomainService.updateCooperateByCarrierId(carrierCooperateInfoSave);
            }
            operateLogApplicationService.reAuthCarrierLog(carrierInfoSave.getId(), carrierInfoSave.getMobile());
        }
    }

    /**
     * 车老板免审判断
     * 免审：姓名、身份证号二要素通过，驾驶证图片未传，准驾车型为空；传驾驶证图片，准驾车型选的其他，则免审。任何不满足则进入客服审核。
     * 免审：审核状态变为已认证，审核人为：系统，审核时间：提交时间+1s；
     *
     * @param carrierInfoSave
     */
    private void cancelApproveCarrierBoss(CarrierInfo carrierInfoSave, UserInfoDTO userInfoDTO) {
        if (userInfoDTO.getAuthStatus() == 2
            && ((StringUtil.isEmpty(carrierInfoSave.getDrivingLicencePic()) && StringUtil.isEmpty(carrierInfoSave.getAllowDrivingModel()))
            || (!StringUtil.isEmpty(carrierInfoSave.getDrivingLicencePic()) && "其他".equals(StringUtil.isEmpty(carrierInfoSave.getAllowDrivingModel()))))) {
            carrierInfoSave.setAuthenticationStatus(CarrierAuthStatusEnum.PASS.getCode());
            carrierInfoSave.setAuthenticationUserId(0L);
            carrierInfoSave.setAuthenticationTime(DateUtil.addSecond(carrierInfoSave.getSubmitTime(), 1));
        }
    }

    /**
     * 运力辅助人免审判断
     * 免审：姓名、身份证号二要素通过，选择入驻企业和平台合作关系生效，且合同生效期内，则免审。任何不满足则进入客服审核。
     * 免审：审核状态变为已认证，审核人为：系统，审核时间：提交时间+1s；
     *
     * @param carrierInfoSave
     */
    private void cancelApproveAuxiliary(CarrierInfo carrierInfoSave, UserInfoDTO userInfoDTO, CarrierCooperateInfo carrierCooperateInfoSave) {
        if (userInfoDTO.getAuthStatus() == 2 && carrierCooperateInfoSave.getEnterFlag() == 1 && carrierCooperateInfoSave.getValidityFlag() == 1) {
            carrierInfoSave.setAuthenticationStatus(CarrierAuthStatusEnum.PASS.getCode());
            carrierInfoSave.setAuthenticationUserId(0L);
            carrierInfoSave.setAuthenticationTime(DateUtil.addSecond(carrierInfoSave.getSubmitTime(), 1));
        }
    }

    /**
     * 辅助人辅助企业是否入驻,是否在合同有效期内
     *
     * @param carrierCooperateInfo
     * @return
     */
    public CarrierCooperateInfo buildCooperateInfo(CarrierCooperateInfo carrierCooperateInfo) {
        EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
        enterpriseQuery.setUnifiedSocialCreditCode(carrierCooperateInfo.getUnifiedSocialCreditCode());
        List<EnterpriseDTO> enterpriseDTOList = enterpriseService.queryEnterpriseList(enterpriseQuery).getResult();
        if (CollectionUtil.isEmpty(enterpriseDTOList)) {
            carrierCooperateInfo.setEnterFlag(YesNoEnum.NAY.getValue());
            carrierCooperateInfo.setValidityFlag(YesNoEnum.NAY.getValue());
            return carrierCooperateInfo;
        }
        carrierCooperateInfo.setEnterFlag(YesNoEnum.YEA.getValue());
        EnterpriseDTO enterpriseDTO = enterpriseDTOList.get(0);
        ContractRunningQuery contractRunningQuery = new ContractRunningQuery();
        contractRunningQuery.setEnterpriseId(enterpriseDTO.getId());
        contractRunningQuery.setContractEndTime(new Date());
        List<ContractPageDTO> contractPageDTOList = contractInfoService.getRunningPage(contractRunningQuery).getResult().getPage().getList();
        if (!CollectionUtil.isEmpty(contractPageDTOList)) {
            carrierCooperateInfo.setValidityFlag(YesNoEnum.YEA.getValue());
        } else {
            carrierCooperateInfo.setValidityFlag(YesNoEnum.NAY.getValue());
        }
        return carrierCooperateInfo;
    }

    /**
     * 校验司机能否注销
     */
    public CheckResultDTO checkLogout(CarrierInfoQuery carrierInfoQuery) {
        return new CheckResultDTO(checkLogoutUser(carrierInfoQuery.getUserId()));
    }

    /**
     * 司机账户资产校验
     */
    private boolean checkLogoutUser(Long userId) {
        // TODO 司机账户资产校验

        return true;
    }

    /**
     * 司机账号注销
     */
    public void logoutUser(CarrierInfoQuery carrierInfoQuery) {
        this.checkLogoutUser(carrierInfoQuery.getUserId());

        userBaseService.logoutUser(carrierInfoQuery.getUserId());
    }

    /**
     * 更新司机端信息
     */
    public void updateCarrierInfo(CarrierInfoCommand command) {
        CarrierInfo query = carrierInfoDomainService.queryByCarrierId(command.getCarrierId());
        if (query == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        //修改司机信息
        CarrierInfo carrierInfo = CarrierInfoAssembler.converterCarrierInfoToCarrierInfo(command);
        int result = carrierInfoDomainService.updateCarrierInfoById(carrierInfo);
        if (result < 1) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_UPDATE_FAIL);
        }
        // 修改辅助人信息
        if (IdentityTypeEnum.CARRIER_BRKR.getSubType().equals(query.getIdentityType())) {
            CarrierCooperateInfo carrierCooperateInfo = CarrierInfoAssembler.converterCarrierInfoToCarrierCooperate(command);
            carrierInfoDomainService.updateCooperateByCarrierId(carrierCooperateInfo);
        }
        // 修改企业信息
        if (IdentityTypeEnum.CARRIER_TCOM_MANAGER.getSubType().equals(query.getIdentityType())) {
            CarrierCompanyInfo carrierCompanyInfo = CarrierInfoAssembler.converterCarrierInfoToCarrierCompany(command);
            carrierInfoDomainService.updateCompanyByCarrierId(carrierCompanyInfo);
        }
        // 通知修改EUC用户的信息
        updateEucUserInfo(carrierInfo, command.getUpdateUserId());
        operateLogApplicationService.updateCarrierLog(command.getCarrierId(), command.getUpdateUserId());
    }

    /**
     * 添加省市区信息
     */
    private void setAreaInfo(CarrierInfo carrierInfo) {
        String idCardNo = carrierInfo.getIdcardNo();
        Long areaCode = Long.parseLong(idCardNo.substring(0, 6));
        AreaQuery query = new AreaQuery(areaCode);
        try {
            ResponseMessage<AreaDTO> responseMessage = areaService.queryAreaByCode(query);
            AreaDTO areasDTO = responseMessage.getResult();
            carrierInfo.setProvinceCode(areasDTO.getProvinceCode().toString());
            carrierInfo.setProvinceName(areasDTO.getProvinceName());
            carrierInfo.setCityCode(areasDTO.getCityCode().toString());
            carrierInfo.setCityName(areasDTO.getCityName());
            carrierInfo.setAreaCode(areasDTO.getCountyCode().toString());
            carrierInfo.setAreaName(areasDTO.getCountyName());
        } catch (Exception e) {
            log.error("根据县编码查询省市区信息异常, userId：{}, areaCode：{}", carrierInfo.getId(), areaCode, e);
        }
    }

    /**
     * 司机审核
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditCarrier(CarrierAuditCommand carrierAuditCommand) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierAuditCommand.getCarrierId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        // label包含二要素异常可以修改身份证
        if (!StringUtil.isEmpty(carrierInfo.getLabel()) && carrierInfo.getLabel().contains("二要素异常")) {
            updateUserNameAndIdCard(carrierAuditCommand.getCarrierId(), carrierAuditCommand.getRealName(), carrierAuditCommand.getIdCardNo());
            carrierInfo.setDrivingLicenceNo(carrierAuditCommand.getDrivingLicenceNo());
        }
        carrierAuditCommand.setDrivingLicenceNo(carrierInfo.getDrivingLicenceNo());
        CarrierInfo bean = CarrierInfoAssembler.converterAuditCarrierInfo(carrierAuditCommand);
        // 驳回原因处理
        if (StringUtil.isNotBlank(carrierAuditCommand.getRejectReason())){
            bean.setRejectReason(auditRejectReasonApplicationService.formattedRejectReason(carrierAuditCommand.getRejectReason()));
            bean.setAuthenticationRemark(auditRejectReasonApplicationService.syncAuditRemark(carrierAuditCommand.getRejectReason()));
            bean.setHistoryRemark(auditRejectReasonApplicationService.syncHistoryRemark(bean.getAuthenticationRemark(),bean.getHistoryRemark()));
        }
        bean.setId(carrierInfo.getId());
        // 更新
        carrierInfoDomainService.updateCarrierInfoById(bean);
        if (carrierInfo.getIdentityType().equals(IdentityTypeEnum.CARRIER_BRKR.getSubType())) {
            // 更新辅助人信息
            CarrierCooperateInfo cooperateInfo = carrierInfoDomainService.queryInitCooperateInfo(carrierInfo.getId());
            if (cooperateInfo == null) {
                throw new CarrierUserException(CarrierUseErrorCodeEnum.COOPERATE_NOT_EXISTS);
            }
            cooperateInfo = CarrierInfoAssembler.buildCooperateInfo(cooperateInfo, carrierAuditCommand);
            carrierInfoDomainService.updateCooperateByCarrierId(cooperateInfo);
        }
        // 通知修改EUC用户的信息
        updateEucUserInfo(bean, carrierAuditCommand.getUpdateUserId());
        // 日志记录
        if (carrierAuditCommand.getAuthStatus() == CarrierAuthStatusEnum.REJECT.getCode()) {
            operateLogApplicationService.rejectCarrierLog(carrierAuditCommand.getCarrierId(), carrierAuditCommand.getAuthUserId());
        } else if (carrierAuditCommand.getAuthStatus() == CarrierAuthStatusEnum.PASS.getCode()) {
            operateLogApplicationService.passCarrierLog(carrierAuditCommand.getCarrierId(), carrierAuditCommand.getAuthUserId());
        }
    }

    /**
     * 修改用户信息后同步到EUC
     * @param carrierInfo
     */
    public void updateEucUserInfo(CarrierInfo carrierInfo, Long updateUserId) {
        //修改同步到EUC
        UserCommand userCommand = new UserCommand();
        userCommand.setId(carrierInfo.getId());
        userCommand.setIdCardFront(carrierInfo.getIdcardPic());
        userCommand.setIdCardBehind(carrierInfo.getIdcardReversePic());
        userCommand.setIdCardStartTime(carrierInfo.getIdcardStartTime());
        userCommand.setIdCardEndTime(carrierInfo.getIdcardEndTime());
        if (carrierInfo.getProvinceCode() != null) {
            userCommand.setIdCardProvinceCode(Integer.parseInt(carrierInfo.getProvinceCode()));
            userCommand.setIdCardProvinceName(carrierInfo.getProvinceName());
        }
        if (carrierInfo.getCityCode() != null) {
            userCommand.setIdCardCityCode(Integer.parseInt(carrierInfo.getCityCode()));
            userCommand.setIdCardCityName(carrierInfo.getCityName());
        }
        if (carrierInfo.getAreaCode() != null) {
            userCommand.setIdCardCountyCode(Integer.parseInt(carrierInfo.getAreaCode()));
            userCommand.setIdCardCountyName(carrierInfo.getAreaName());
        }
        if (carrierInfo.getUserTag() != null) {
            userCommand.setUserTag(carrierInfo.getUserTag());
        }
        userCommand.setIdCardAddress(carrierInfo.getAddress());
        userCommand.setUpdateUserId(updateUserId);
        userBaseService.editInfo(userCommand);
    }

    /**
     * 物流公司审核审核
     */
    @Transactional(rollbackFor = Exception.class)
    public void auditCompany(CompanyAuditCommand companyAuditCommand) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(companyAuditCommand.getCarrierId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        // label包含二要素异常可以修改身份证
        if (!StringUtil.isEmpty(carrierInfo.getLabel()) && carrierInfo.getLabel().contains("二要素异常")) {
            updateUserNameAndIdCard(companyAuditCommand.getCarrierId(), companyAuditCommand.getRealName(), companyAuditCommand.getIdCardNo());
        }
        CarrierInfo bean = CarrierInfoAssembler.converterAuditCompanyInfo(companyAuditCommand);
        // 驳回原因处理
        if (StringUtil.isNotBlank(companyAuditCommand.getRejectReason())){
            bean.setRejectReason(auditRejectReasonApplicationService.formattedRejectReason(companyAuditCommand.getRejectReason()));
            bean.setAuthenticationRemark(auditRejectReasonApplicationService.syncAuditRemark(companyAuditCommand.getRejectReason()));
            bean.setHistoryRemark(auditRejectReasonApplicationService.syncHistoryRemark(bean.getAuthenticationRemark(),bean.getHistoryRemark()));
        }
        bean.setId(carrierInfo.getId());
        // 更新司机信息和物流公司信息
        carrierInfoDomainService.updateCarrierInfoById(bean);
        CarrierCompanyInfo carrierCompanyInfo = carrierInfoDomainService.queryCompayInfoByCarrierId(carrierInfo.getId());
        if (carrierCompanyInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.COMPANY_NOT_EXISTS);
        }
        carrierCompanyInfo = CarrierInfoAssembler.buildCompanyInfo(carrierCompanyInfo, companyAuditCommand, carrierInfo.getIdentityType());
        carrierInfoDomainService.updateCompanyByCarrierId(carrierCompanyInfo);
        // 通知修改EUC用户的信息
        updateEucUserInfo(bean, companyAuditCommand.getUpdateUserId());
        // 日志记录
        if (companyAuditCommand.getAuthStatus() == CarrierAuthStatusEnum.REJECT.getCode()) {
            operateLogApplicationService.rejectCarrierLog(companyAuditCommand.getCarrierId(), companyAuditCommand.getAuthUserId());
        } else if (companyAuditCommand.getAuthStatus() == CarrierAuthStatusEnum.PASS.getCode()) {
            operateLogApplicationService.passCarrierLog(companyAuditCommand.getCarrierId(), companyAuditCommand.getAuthUserId());
        }
    }

    /**
     * 二要素异常可以修改身份证信息
     * @param carrierId
     * @param realName
     * @param idCardNo
     */
    private void updateUserNameAndIdCard(Long carrierId, String realName, String idCardNo) {
        UserBaseInfoQuery userBaseInfoQuery = new UserBaseInfoQuery();
        userBaseInfoQuery.setId(carrierId);
        UserInfoDTO userInfoDTO = userBaseService.queryById(userBaseInfoQuery).getResult();
        if (userInfoDTO == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        if (userInfoDTO.getAuthStatus().equals(2)) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.ALREADY_AUTH);
        }
        UserCommand userCommand = KcBeanConverter.toBean(userInfoDTO, UserCommand.class);
        userCommand.setRealName(realName);
        userCommand.setIdCardNo(idCardNo);
        userBaseService.editInfo(userCommand);
    }

    /**
     * 冻结司机
     */
    public void carrierLock(OperateCommand command) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(command.getCarrierId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        if (YesNoEnum.YEA.getValue().equals(carrierInfo.getIsLock())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_LOCKED);
        }
        CarrierInfo update = new CarrierInfo();
        update.setId(command.getCarrierId());
        update.setUpdateUserId(command.getOperatorId());
        update.setIsLock(YesNoEnum.YEA.getValue());
        carrierInfoDomainService.updateCarrierInfoById(update);
    }

    /**
     * 解锁司机
     */
    public void carrierUnLock(OperateCommand command) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(command.getCarrierId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        if (YesNoEnum.NAY.getValue().equals(carrierInfo.getIsLock())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_LOCKED);
        }
        CarrierInfo update = new CarrierInfo();
        update.setId(command.getCarrierId());
        update.setUpdateUserId(command.getOperatorId());
        update.setIsLock(YesNoEnum.NAY.getValue());
        carrierInfoDomainService.updateCarrierInfoById(update);
    }

    /**
     * 删除司机
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(OperateCommand command) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(command.getCarrierId());
        if (carrierInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.USER_IS_NOT_EXISTS);
        }
        if (carrierInfo.getDeleted().equals(YesNoEnum.YEA.getValue())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_DELETED);
        }
        CarrierInfo update = new CarrierInfo();
        update.setId(command.getCarrierId());
        update.setUpdateUserId(command.getOperatorId());
        update.setDeleted(YesNoEnum.YEA.getValue());
        carrierInfoDomainService.updateCarrierInfoById(update);
        // 用户注销
        DelUserCommand delUserCommand = new DelUserCommand();
        delUserCommand.setUserId(command.getCarrierId());
        delUserCommand.setDelUserId(command.getOperatorId());
        userBaseService.logoutUser(delUserCommand);
    }

    public PageInfoDTO<CooperateEnterpriseDTO> queryCarrierCooperateEnterprisePage(CooperateEnterpriseQuery query) {
        CooperateEnterpriseCondition condition = KcBeanConverter.toBean(query, CooperateEnterpriseCondition.class);
        KcPage<CooperateEnterpriseDTO> pageEntity = carrierInfoDomainService.queryCooperateEnterpriseList(condition);
        return KcPageConverter.toPageInfoDTO(pageEntity, CooperateEnterpriseDTO.class);
    }

    /**
     * 修改辅助人辅助企业是否入驻
     *
     * @param command
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCooperateEnterprise(CooperateEnterpriseCommand command) {
        //修改两个地方,carrier_info和carrier_assistant_enterprise_ref
        CarrierCooperateInfo cooperateInfo = carrierInfoDomainService.getCooperateInfoById(command.getId());
        if (cooperateInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.COOPERATE_NOT_EXISTS);
        }
        Long carrierId = cooperateInfo.getCarrierId();
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(carrierId);
        if (cooperateInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.USER_IS_NOT_EXISTS);
        }
        carrierInfo.setAuxiliaryEnterpriseEnterFlag(command.getIsEnter());
        carrierInfoDomainService.updateCarrierInfoById(carrierInfo);
        if (cooperateInfo == null) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.COOPERATE_NOT_EXISTS);
        }
        cooperateInfo.setEnterFlag(command.getIsEnter());
        carrierInfoDomainService.updateCooperateByCarrierId(cooperateInfo);
    }

    /**
     * 车队长转为司机
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeToDriver(ChangeIdentityCommand changeIdentityCommand) {
        Long userId = changeIdentityCommand.getUserId();
        //校验能不能变更
        Integer vehicleCount = checkVehicleCount(userId);
        Integer checkCount = checkChangeIdentityCondition(userId);
        if (vehicleCount > 1 || checkCount > 0) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CAN_NOT_CHANGE_DRIVER);
        }
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(userId);
        if (!IdentityTypeEnum.CARRIER_SFLTOP.getSubType().equals(carrierInfo.getIdentityType())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.IDENTITY_TYPE_ERROR);
        }
    }

    /**
     * 司机转成车队长
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeToCarrier(ChangeIdentityCommand changeIdentityCommand) {
        Long userId = changeIdentityCommand.getUserId();
        //校验能不能变更
        Integer checkCount = checkChangeIdentityCondition(userId);
        if (checkCount > 0) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CAN_NOT_CHANGE_CARRIER_BOSS);
        }
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(userId);
        if (!IdentityTypeEnum.CARRIER_DRIVER.getSubType().equals(carrierInfo.getIdentityType())) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.IDENTITY_TYPE_ERROR);
        }
        //我的车队长下的车和邀请关系删除
        //转到车队长后我的车辆关系去掉driver_id
        //修改身份类型
    }

    /**
     * 校验是否可以转换身份
     * 进行中的运单数>0不满足
     * 代收给我的订单数>0不满足
     * 代收关系>0不满足
     */
    private Integer checkChangeIdentityCondition(Long userId) {
        //TODO 进行中的订单数
        //TODO 代收给我的订单数
        //TODO 代收关系
        return 0;
    }

    /**
     * 校验是否可以转换身份(车队长转司机)
     * 车辆数>1不满足
     */
    private Integer checkVehicleCount(Long userId) {
        VehicleInfo vehicleInfo = new VehicleInfo();
        vehicleInfo.setCarrierId(userId);
        vehicleInfo.setIsDel(YesNoEnum.NAY.getValue());
        return vehicleInfoDomainService.selectCount(vehicleInfo);
    }

    /**
     * 更新驾驶证
     * @param command
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDrivingLicence(DrivingLicenceCommand command) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByCarrierId(command.getCarrierId());
        if(carrierInfo == null){
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_IS_NOT_EXISTS);
        }
        if(carrierInfo.getAuthenticationStatus() != CarrierInfoEnums.AuthenticationStatusEnum.VERIFIED.getCode()){
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_NOT_PASS);
        }
        if(command.getDrivingLicenceNo() != null && !command.getDrivingLicenceNo().equals(carrierInfo.getDrivingLicenceNo())){
            throw new CarrierUserException(CarrierUseErrorCodeEnum.CARRIER_NOT_OWNER);
        }
        QualificationInfo qualificationInfo = KcBeanConverter.toBean(command, QualificationInfo.class);
        qualificationInfo.setBizId(command.getCarrierId());
        qualificationInfo.setBizType(BizTypeEnum.BIZ_CARRIER.getCode());
        QualificationInfo byBizId = qualificationInfoDomainService.getByBizId(qualificationInfo);
        if(byBizId != null){
            //修改
            byBizId.setDrivingLicencePic(command.getDrivingLicencePic());
            byBizId.setDrivingLicenceNo(command.getDrivingLicenceNo());
            byBizId.setAllowDrivingModel(command.getAllowDrivingModel());
            byBizId.setDriverLicenseEndTime(command.getDriverLicenseEndTime());
            /*if(command.getIsChangedAllowDrivingModel() == YesNoEnum.YEA.getValue().intValue()){
                byBizId.setAuthenticationStatus(CarrierInfoEnums.AuthenticationStatusEnum.VERIFIED.getCode());
                //TODO 更新司机表驾驶证信息

             }else{
                byBizId.setAuthenticationStatus(CarrierInfoEnums.AuthenticationStatusEnum.PENDING_REVIEW.getCode());
            }*/
            byBizId.setAuthenticationStatus(CarrierInfoEnums.AuthenticationStatusEnum.PENDING_REVIEW.getCode());
            qualificationInfoDomainService.updateById(byBizId);
        }else {
            qualificationInfo.setAuthenticationStatus(CarrierInfoEnums.AuthenticationStatusEnum.PENDING_REVIEW.getCode());
            qualificationInfo.setSubmitTime(new Date());
            qualificationInfo.setModifyTime(new Date());
            qualificationInfo.setIsDel(0);
            qualificationInfoDomainService.insert(qualificationInfo);
        }
        return Boolean.TRUE;
    }

    /**
     * 查询司机表信息
     * @param carrierInfoQuery
     * @return
     */
    public CarrierInfoDTO getCarrierInfo(CarrierInfoQuery carrierInfoQuery) {
        CarrierInfo carrierInfo = KcBeanConverter.toBean(carrierInfoQuery, CarrierInfo.class);
        carrierInfo.setId(carrierInfoQuery.getUserId());
        return KcBeanConverter.toBean(carrierInfoDomainService.getCarrierInfo(carrierInfo), CarrierInfoDTO.class);
    }

    /**
     * 调度单查询司机(不返回车牌号)
     * @param mobileQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchDriverInfo(MobileQuery mobileQuery) {
        List<DriverInfo> driverInfoList = KcBeanConverter.toList(carrierInfoDomainService.queryDispatchDriverInfo(mobileQuery.getMobile()), DriverInfo.class);
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        dispatchCarrierInfoDTO.setDriverInfo(driverInfoList);
        return dispatchCarrierInfoDTO;
    }


    /**
     * 查询司机及关联车辆
     * @param dispatchCarrierQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchDriverAndVehicleInfo(DispatchCarrierQuery dispatchCarrierQuery) {
        List<DriverInfo> driverInfoList = KcBeanConverter.toList(carrierInfoDomainService.queryDispatchDriverAndVehicleInfo(dispatchCarrierQuery.getQueryInfo()), DriverInfo.class);
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        dispatchCarrierInfoDTO.setDriverInfo(driverInfoList);
        return dispatchCarrierInfoDTO;
    }


    /**
     * 查询承运商
     * @param mobileQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchCompanyInfo(MobileQuery mobileQuery) {
        List<CompanyInfo> companyInfoList = KcBeanConverter.toList(carrierInfoDomainService.queryDispatchCompanyInfo(mobileQuery.getMobile()), CompanyInfo.class);
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        dispatchCarrierInfoDTO.setCompanyInfo(companyInfoList);
        return dispatchCarrierInfoDTO;
    }


    /**
     * 查询承运商/物流辅助服务商
     * @param mobileQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchCompanyAndAuxiliaryInfo(MobileQuery mobileQuery) {
        List<CompanyInfo> companyInfoList = KcBeanConverter.toList(carrierInfoDomainService.queryDispatchCompanyAndAuxiliaryInfo(mobileQuery.getMobile()), CompanyInfo.class);
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        dispatchCarrierInfoDTO.setCompanyInfo(companyInfoList);
        return dispatchCarrierInfoDTO;
    }


    /**
     * 查询物流辅助服务商
     * @param mobileQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchAuxiliaryInfo(MobileQuery mobileQuery) {
        List<CompanyInfo> companyInfoList = KcBeanConverter.toList(carrierInfoDomainService.queryDispatchAuxiliaryInfo(mobileQuery.getMobile()), CompanyInfo.class);
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        dispatchCarrierInfoDTO.setCompanyInfo(companyInfoList);
        return dispatchCarrierInfoDTO;
    }


    /**
     * 调度单回显运力范围
     * @param dispatchCarrierQuery
     * @return
     */
    public DispatchCarrierInfoDTO queryDispatchCarrierInfo(DispatchCarrierQuery dispatchCarrierQuery) {
        DispatchCarrierInfoDTO dispatchCarrierInfoDTO = new DispatchCarrierInfoDTO();
        List<CarrierInfo> carrierInfoList = carrierInfoDomainService.getByIds(dispatchCarrierQuery.getCarrierIds());
        if (CollectionUtil.isEmpty(carrierInfoList)) {
            return new DispatchCarrierInfoDTO();
        }
        List<CarrierInfo> driverList = carrierInfoList.stream().filter(carrierInfo ->
                IdentityTypeEnum.CARRIER_DRIVER.getSubType().equals(carrierInfo.getIdentityType())).collect(Collectors.toList());
        List<Long> companyIdList = carrierInfoList.stream().filter(carrierInfo ->
                IdentityTypeEnum.CARRIER_SFLTOP.getSubType().equals(carrierInfo.getIdentityType())
                || IdentityTypeEnum.CARRIER_TCOM_MANAGER.getSubType().equals(carrierInfo.getIdentityType())
                || IdentityTypeEnum.CARRIER_TDSPR.getSubType().equals(carrierInfo.getIdentityType())).map(CarrierInfo::getId).collect(Collectors.toList());
        List<CompanyDispatchInfo> companyDispatchInfoList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(companyIdList)) {
            companyDispatchInfoList = carrierInfoDomainService.queryDispatchCarrierInfo(companyIdList);
        }
        List<DriverInfo> driverInfoList = new ArrayList<>();
        for (CarrierInfo carrierInfo : driverList) {
            DriverInfo driverInfo = new DriverInfo();
            driverInfo.setDriverName(carrierInfo.getName());
            driverInfo.setMobile(carrierInfo.getMobile().substring(7));
            driverInfoList.add(driverInfo);
        }
        List<CompanyInfo> companyInfoList = KcBeanConverter.toList(companyDispatchInfoList, CompanyInfo.class);
        Long vehicleCount = companyInfoList.stream().map(CompanyInfo::getVehicleCount).count() + driverInfoList.size();
        Long driverCount = companyInfoList.stream().map(CompanyInfo::getDriverCount).count() + driverInfoList.size();
        dispatchCarrierInfoDTO.setDriverInfo(driverInfoList);
        dispatchCarrierInfoDTO.setCompanyInfo(companyInfoList);
        dispatchCarrierInfoDTO.setVehicleCount(vehicleCount.intValue());
        dispatchCarrierInfoDTO.setDriverCount(driverCount.intValue());
        dispatchCarrierInfoDTO.setCompanyCount(companyInfoList.size());
        return dispatchCarrierInfoDTO;
    }

    /**
     * 查询司机所属组织
     * @param carrierInfoQuery
     * @return
     */
    public List<Long> queryDispatchDriverOrg(CarrierInfoQuery carrierInfoQuery) {
        return carrierInfoDomainService.queryDispatchDriverOrg(carrierInfoQuery.getUserId());
    }

    /**
     * 获取驾驶证信息
     * @param carrierId
     * @return
     */
    public QualificationDTO getDrivingLicence(Long carrierId) {
        QualificationInfo qi = new QualificationInfo();
        qi.setBizId(carrierId);
        qi.setBizType(BizTypeEnum.BIZ_CARRIER.getCode());
        QualificationInfo qualificationInfo = qualificationInfoDomainService.getByBizId(qi);
        QualificationDTO qualificationDTO = KcBeanConverter.toBean(qualificationInfo, QualificationDTO.class);
        if(qualificationDTO == null){
            return qualificationDTO;
        }
        FileUrlQuery condition = new FileUrlQuery();
        List<String> keys = new ArrayList<>();
        keys.add(qualificationDTO.getDrivingLicencePic());
        condition.setKeys(keys);
        ResponseMessage<List<FileUrlDTO>> urlByKeys = fileRemoteService.getUrlByKeys(condition);
        qualificationDTO.setDrivingLicencePicDesc(urlByKeys.getResult().get(0).getUrl());
        qualificationDTO.setCarrierId(carrierId);
        return qualificationDTO;
    }

    /**
     * 根据ID查询司机信息
     * @param idListQuery
     * @return
     */
    public List<CarrierInfoDTO> getCarrierInfoByIdList(IdListQuery idListQuery) {
        List<CarrierInfo> carrierInfoList = carrierInfoDomainService.getByIds(idListQuery.getIdList());
        return KcBeanConverter.toList(carrierInfoList, CarrierInfoDTO.class);
    }

    /**
     * 根据ID查询运力信息
     * @param idListQuery
     * @return
     */
    public List<VipDispatchCarrierInfoDTO> queryCarrierInfoByIdList(IdListQuery idListQuery) {
        List<Long> idList = idListQuery.getIdList();
        List<CarrierInfo> carrierInfoList = carrierInfoDomainService.getByIds(idList);
        List<VipDispatchCarrierInfoDTO> vipDispatchCarrierInfoDTOList = KcBeanConverter.toList(carrierInfoList, VipDispatchCarrierInfoDTO.class);
        if (CollectionUtil.isEmpty(carrierInfoList)) {
            return new ArrayList<>();
        }
        List<CarrierInfo> companyList = carrierInfoList.stream().filter(carrierInfo ->
                carrierInfo.getIdentityType() == IdentityTypeEnum.CARRIER_TCOM_MANAGER.getSubType()).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(companyList)) {
            List<CarrierCompanyInfo> carrierCompanyInfoList = carrierInfoDomainService.queryCompanyInfoByCarrierIdList(
                    companyList.stream().map(CarrierInfo::getId).collect(Collectors.toList()));
            Map<Long, String> map = carrierCompanyInfoList.stream().filter(carrierCompanyInfo -> carrierCompanyInfo.getCarrierId() != null)
                    .collect(Collectors.toMap(CarrierCompanyInfo::getCarrierId, carrierCompanyInfo -> carrierCompanyInfo.getEnterpriseName()));
            for (VipDispatchCarrierInfoDTO vipDispatchCarrierInfoDTO : vipDispatchCarrierInfoDTOList) {
                vipDispatchCarrierInfoDTO.setCompanyName(map.get(vipDispatchCarrierInfoDTO.getId()));
            }
        }
        return vipDispatchCarrierInfoDTOList;
    }

    /**
     * TMS查询司机信息
     * @return
     */
    public PageInfoDTO<TmsDriverInfoDTO> queryTmsDriverInfoPage(TmsDriverInfoQuery tmsDriverInfoQuery) {
        TmsDriverInfoCondition condition = KcBeanConverter.toBean(tmsDriverInfoQuery, TmsDriverInfoCondition.class);
        KcPage<TmsDriverInfo> tmsDriverInfoKcPage = carrierInfoDomainService.queryTmsDriverInfoPage(condition);
        return KcPageConverter.toPageInfoDTO(tmsDriverInfoKcPage, TmsDriverInfoDTO.class);
    }

    /**
     * TMS删除司机
     * @param tmsDriverInfoCommand
     */
    public void deleteTmsDriver(TmsDriverInfoCommand tmsDriverInfoCommand) {
        // 查询绑定车辆
        CarrierMappingQuery carrierMappingQuery = new CarrierMappingQuery();
        carrierMappingQuery.setDriverId(tmsDriverInfoCommand.getUserId());
        carrierMappingQuery.setIsDel(YesNoEnum.NAY.getValue());
        List<CarrierMappingInfo> carrierMappingInfoList = carrierMappingDomainService.queryCarrierMappingInfo(carrierMappingQuery);
        if (!CollectionUtil.isEmpty(carrierMappingInfoList)) {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.ALREADY_BIND_VEHICLE);
        }
        // 用户服务删除
        DelUserCommand delUserCommand = KcBeanConverter.toBean(tmsDriverInfoCommand, DelUserCommand.class);
        userBaseService.logoutUser(delUserCommand);
        // 司机表删除
        carrierInfoDomainService.deleteTmsDriver(tmsDriverInfoCommand.getUserId());
        // carrier_driver逻辑删除
        CarrierDriverQuery carrierDriverQuery = new CarrierDriverQuery();
        carrierDriverQuery.setDriverId(tmsDriverInfoCommand.getUserId());
        carrierDriverQuery.setIsDel(YesNoEnum.NAY.getValue());
        List<CarrierDriverDTO> carrierDriverDTOList = carrierDriverApplicationService.queryCarrierDriver(carrierDriverQuery);
        if (CollectionUtil.isEmpty(carrierDriverDTOList)) {
            return;
        }
        CarrierDriverCommand carrierDriverCommand = new CarrierDriverCommand();
        carrierDriverCommand.setId(carrierDriverDTOList.get(0).getId());
        carrierDriverCommand.setIsDel(YesNoEnum.YEA.getValue());
        carrierDriverApplicationService.updateCarrierDriverInfo(carrierDriverCommand);
    }

    /**
     * TMS取消认证
     * @param carrierInfoQuery
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelTmsApprove(CarrierInfoQuery carrierInfoQuery) {
        CarrierInfo carrierInfo = carrierInfoDomainService.queryByUserId(carrierInfoQuery.getUserId());
        if (carrierInfo != null && CarrierAuthStatusEnum.WAITING.getCode() == carrierInfo.getAuthenticationStatus()) {
            carrierInfo.setAuthenticationStatus(CarrierAuthStatusEnum.REJECT.getCode());
            carrierInfoDomainService.updateCarrierInfoById(carrierInfo);
        } else {
            throw new CarrierUserException(CarrierUseErrorCodeEnum.ALREADY_PASS_AUTH);
        }
    }

}
